<?php

namespace app\admin\controller\vppz;

use think\Db;
use think\Exception;
use think\Session;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Bdhospital extends Base
{

    /**
     * Hospital模型对象
     * @var \app\admin\model\vppz\Hospital
     */
    protected $model = null;

	protected $searchFields = ['id','name','area.name','rank','label'];
	protected $multiFields = ['use_switch'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\Hospital;
        $this->KeshiListModel = new \app\admin\model\vppz\Keshi;
        $this->adminModel = new \app\admin\model\Admin;
        $this->couponModel = new \app\admin\model\vppz\Coupon;
        $this->KeshiHospitalModel = new \app\admin\model\vppz\KeshiHospital;
        $this->authGroupAccessModel = new \app\admin\model\AuthGroupAccess;

		// 给数据附加当前appid，appid由Base负责解析
		$this->model::event('before_insert', function ($row){
			$row->app_id=$this->app_id;
		});
        $config = \think\App::initCommon();
		$this->model::event('before_insert', function ($row){return $this->beforeSave($row);});
		$this->model::event('before_update', function ($row){return $this->beforeSave($row);});
        $this->assign('hospital_level',$config['hospital_level']);
        $this->assign('hospital_label',$config['hospital_label']);
        $KeshiList = $this->KeshiListModel->where('is_local','=',1)->select();
        $this->assign('KeshiList',$KeshiList);
    }

    protected function filter(&$query)
    {
        // 添加性别筛选条件
        if ($this->request->has('rank')) {
            $rank = $this->request->param('rank');
            if ($rank !== '') {
                $query->where('rank', $rank);
            }
        }
        if ($this->request->has('label')) {
            $label = $this->request->param('label');
            if ($label !== '') {
                $query->where('label', $label);
            }
        }
    }
	// 处理前端输入的城市，分为三段存储
	protected function beforeSave($row){
		if(in_array($this->request->action(),['add','edit'])){
			$city = explode('/',$row->city);
			if(count($city)!=3){
				//$this->error('请选择到区');
				//echo '测试';
				exception('所在区域请选择区县');
				return false;
			}
			$row->province=$city[0];
			$row->city=$city[1];
			$row->district=$city[2];
		}
	}



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $config = \think\App::initCommon();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $admin = Session::get("admin");
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage_custom();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			$adminAreasWhere=$this->adminAreasWhere('area_id');
            $searchWhere = [];
            if($admin['is_pingtai'] != 1){
                $searchWhere = ['admin_id'=>$admin['id']];
            }
            $list = $this->model
                    ->with(['area'])
                    ->where('is_local','=',1)
                    ->where($where)->where($adminAreasWhere)->where($searchWhere)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
//                $row->rank = $config['hospital_level'][$row->rank]??'三级';
//                $row->label = $config['hospital_label'][$row->label]??'综合医院';
                $row->getRelation('area')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

		//$areas = $this->adminAreas();
		//var_dump($areas);
		//var_dump([5,4]);


        return $this->view->fetch();
    }
    /**
	 * 重载selectpage，实现对管理员权限的过滤
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage_custom()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }

				// 自定义管理员权限筛选
				$adminAreasWhere=$this->adminAreasWhere('id');
				$query->where($adminAreasWhere);
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }

        $list = [];
        $total = $this->model->where($where)->where(array(
                'is_local'=>1
            ))->whereNull('deletetime')->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)->where(array(
                'is_local'=>1
            ))->whereNull('deletetime')
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
 /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->modelValidate = true;
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $form = $this->preExcludeFields($params);
            $result = false;
            Db::startTrans();
            try {
                $adminNote = $this->adminModel->where(['username'=>$form['admin_mobile']])->find();
                if(empty($adminNote) === FALSE){
                    $this->model->rollback();
					$this->error('管理员账号已经存在，重试看看呢');
                }
                $salt = \fast\Random::alnum();
                //添加社区管理中心账号
                $adminData = array(
                    'username'=>$form['admin_mobile'],
                    'password'=>\app\common\library\Auth::instance()->getEncryptPassword($form['password'], $salt),
                    'salt'=>$salt,
                    'is_pingtai'=>2,
                    'avatar'=>'/assets/img/avatar.png'
                );
                $this->adminModel->save($adminData);
                $admin_id =$this->adminModel->id;
                //保存医院
                $hospital=array(
					'name'=>$form['name'],
                    'intro'=>$form['intro'],
                    'area_id'=>$form['area_id'],
                    'avatar'=>$form['avatar']??'',
                    'rank'=>$form['rank'],
                    'label'=>$form['label'],
                    'province'=>$form['province']??'',
                    'city'=>$form['city']??'',
                    'district'=>$form['district']??'',
                    'lng'=>$form['lng'],
                    'lat'=>$form['lat'],
                    'address'=>$form['address'],
                    'admin_id'=>$admin_id,
                    'admin_mobile'=>$form['admin_mobile'],
                    'password'=>$form['password'],
                    'is_local'=>1,
                    'is_top'=>$form['is_top'],
                    'content'=>$form['content'],
                    'use_switch'=>$form['use_switch'],
                    'has_coupon'=>$form['has_coupon']??0,
                    'has_zhekou_coupon'=>$form['has_zhekou_coupon']??0,
                    'page'=>$form['page'],
                    'appid'=>$form['appid']
				);
				$ret=$this->model->save($hospital);
                $hospitalid = $this->model->id;
                if(empty($ret) || empty($hospitalid)){
                    DB::rollback();
					$this->error('服务器刚刚走神了，重试看看呢');
				}
                Db::commit();
                $this->success();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        return parent::add();
    }
    public function editpassword($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $form = $this->preExcludeFields($params);

        if($form['password'] != $form['repassword']){
            $this->error('两次密码不一致');
        }
        $result = false;
        try {
            $salt = \fast\Random::alnum();
            //添加社区管理中心账号
            $adminData = array(
                'password'=>\app\common\library\Auth::instance()->getEncryptPassword($form['password'], $salt),
                'salt'=>$salt,
                'updatetime'=>time()
            );
            $res = $this->adminModel->where(['id'=>$row['admin_id']])->find();
            if(empty($res) === FALSE) {
                $ret = $this->adminModel->where(['id' => $row['admin_id']])->update($adminData);
            }else{
                $adminData = array(
                    'username'=>$row['admin_mobile'],
                    'password'=>\app\common\library\Auth::instance()->getEncryptPassword($form['password'], $salt),
                    'salt'=>$salt,
                    'is_pingtai'=>2,
                    'avatar'=>'/assets/img/avatar.png'
                );
                $ret = $this->adminModel->create($adminData);
                $admin_id = $ret->getLastInsID();
                $this->model->where(['id'=>$ids])->update(array(
                    'admin_id'=>$admin_id,
                    'updatetime'=>time()
                ));
                $opera[] = $this->authGroupAccessModel->save(array(
                    'uid'=>$admin_id,
                    'group_id'=>13
                ));
            }
            if(empty($ret)){
                $this->error('服务器刚刚走神了，重试看看呢');
            }
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $keshi = $this->KeshiHospitalModel->where('hospitalid','=',$row['id'])->find();
            if(empty($keshi)){
                $row->keshi = "";
            }else {
                $row->keshi = $keshi['ksid'];
            }
            //判断当前医院是否配置过优惠券
            $has_coupon = $this->couponModel->where(array(
                'hospitalid'=>$row['id'],
                'type'=>1
            ))->value('id');

            $has_zhekou_coupon = $this->couponModel->where(array(
                'hospitalid'=>$row['id'],
                'type'=>2
            ))->value('id');
            $this->view->assign('row', $row);
            $this->view->assign('has_coupon', $has_coupon);
            $this->view->assign('has_zhekou_coupon', $has_zhekou_coupon);
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $form = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
                $adminNote = $this->adminModel->where(['username'=>$form['admin_mobile']])->find();
                if(empty($adminNote) === FALSE && $row['admin_id'] != $adminNote['id']){
                    $this->model->rollback();
					$this->error('管理员账号已经存在，换一个试看看呢');
                }
                $salt = \fast\Random::alnum();
                if($row['admin_id'] == 0) {
                    //添加社区管理中心账号
                    $adminData = array(
                        'username' => $form['admin_mobile'],
                        'password' => \app\common\library\Auth::instance()->getEncryptPassword($form['password'], $salt),
                        'salt' => $salt,
                        'is_pingtai' => 2,
                        'avatar' => '/assets/img/avatar.png'
                    );
                    $this->adminModel->save($adminData);
                    $admin_id =$this->adminModel->id;
                }else{
                    $adminNote = $this->adminModel->where(['id'=>$row['admin_id']])->update(array(
                        'username' => $form['admin_mobile'],
                        'password' => \app\common\library\Auth::instance()->getEncryptPassword($form['password'], $salt),
                        'salt' => $salt,
                        'updatetime'=>time()
                    ));
                    $admin_id = $row['admin_id'];
                }
            //保存医院
                $hospital=array(
					'name'=>$form['name'],
                    'intro'=>$form['intro'],
                    'area_id'=>$form['area_id'],
                    'avatar'=>$form['avatar']??'',
                    'rank'=>$form['rank'],
                    'label'=>$form['label'],
                    'province'=>$form['province']??'',
                    'city'=>$form['city']??'',
                    'district'=>$form['district']??'',
                    'lng'=>$form['lng'],
                    'lat'=>$form['lat'],
                    'address'=>$form['address'],
                    'admin_mobile'=>$form['admin_mobile'],
                    'password'=>$form['password'],
                    'admin_id'=>$admin_id,
                    'is_local'=>1,
                    'is_top'=>$form['is_top'],
                    'content'=>$form['content'],
                    'use_switch'=>$form['use_switch'],
                    'has_coupon'=>$form['has_coupon']??0,
                    'has_zhekou_coupon'=>$form['has_zhekou_coupon']??0,
                    'page'=>$form['page'],
                    'updatetime'=>time(),
                    'appid'=>$form['appid']
				);
				$ret=$this->model->where('id','=',$row['id'])->update($hospital);
                if(empty($ret)){
                    DB::rollback();
                    $result = false;
					$this->error('服务器刚刚走神了，重试看看呢');
				}
                $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();

    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->KeshiHospitalModel->whereIn('hospitalid',$ids)->delete();
        $this->model->whereIn('id',$ids)->delete();
        $this->success();
    }
}
